package com.kgc.itrip.dao.impl;

import com.kgc.itrip.common.Constants;
import com.kgc.itrip.common.Page;
import com.kgc.itrip.dao.SolrDao;
import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Repository
public class SolrDaoImpl<T> implements SolrDao<T> {
    @Resource
    private HttpSolrClient solrClient;

    @Override
    public List<T> listQuery(String coreName, SolrQuery solrQuery, Integer size, Class clazz) throws IOException, SolrServerException {
        //设置xml解析器
        ResponseParser parser = new XMLResponseParser();
        solrClient.setParser(parser);
        size = size==null ? Constants.DEFAULT_PAGE_SIZE : size;
        solrQuery.setStart((1-1)*size);
        solrQuery.setRows(size);
        //使用solrClient取查询：
        QueryResponse response = solrClient.query(coreName, solrQuery);
        //取出查询出的数据集合
        List<T> beans = response.getBeans(clazz);
        return beans;
    }

    @Override
    public Page<T> searchByCondition(String coreName,SolrQuery solrQuery, Integer pageNo, Integer size, Class clazz) throws IOException, SolrServerException {
        //设置xml解析器
        ResponseParser parser = new XMLResponseParser();
        solrClient.setParser(parser);
        //设置分页条件
        pageNo = pageNo==null ? Constants.DEFAULT_PAGE_NO : pageNo;
        size = size==null ? Constants.DEFAULT_PAGE_SIZE : size;
        solrQuery.setStart((pageNo-1)*size);
        solrQuery.setRows(size);
        //使用solrClient取查询：
        QueryResponse response = solrClient.query(coreName, solrQuery);
        //取出查询出的数据集合
        List<T> beans = response.getBeans(clazz);
        SolrDocumentList results = response.getResults();
        Page<T> page = new Page<T>(pageNo,size,(int)results.getNumFound());
        //设置查询到的数据集合
        page.setRows(beans);
        return page;
    }
}

